package com.chinaV.controller;

import com.chinaV.pojo.User;
import com.chinaV.uitls.DBConnection;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


@WebServlet(value = {"/login"})
public class Login extends HttpServlet {

    private DBConnection db = new DBConnection();

    public Login() {
    }

    public User userLogin(String username, String password) {
        String sql = "SELECT * FROM user WHERE username = ? AND password = ?";
        User user = null;
        try {
            PreparedStatement statement = this.db.getConn().prepareStatement(sql);
            statement.setString(1, username);
            statement.setString(2, password);
            ResultSet resultSet = statement.executeQuery();
            if (resultSet.next()) {
                // 从数据库结果集中获取用户信息
                String uid = resultSet.getString("uid");
                String dbUsername = resultSet.getString("username");
                String dbPassword = resultSet.getString("password");
                String email = resultSet.getString("email");
                String phone = resultSet.getString("phone");
                // 创建User对象
                user = new User(Integer.parseInt(uid), dbUsername, dbPassword, email, phone);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return null;
        }

        return user;
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        // 获取表单数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = userLogin(username, password);
        if (user != null) {
            // Cookie 方式
//            Cookie cookie = new Cookie("user", username);
//            resp.addCookie(cookie);

            // Session 方式
            HttpSession session = req.getSession();
            session.setAttribute("user", user);
            req.getRequestDispatcher("/index.jsp").forward(req, resp);
//            resp.sendRedirect("/index.jsp");
        } else {
            resp.sendRedirect("/fail.html");
        }
    }

}

